package com.cskaoyan.transfer;


import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

// 转账的案例
public class TransferDemo {


    // 主方法
    public static void main(String[] args) {

        Boolean ret = transfer("风华哥", "长风", 1000);

        if (ret) {
            System.out.println("转账成功！");
        }else {
            System.out.println("转账失败！");
        }

    }



    /**
     *
     * @param fromName 转账发起人
     * @param toName 目标账户
     * @param money 金额
     * @return 转账成功与否
     */
    // 转账的方法
    public static Boolean transfer(String fromName,String toName,Integer money){

        Connection connection = JDBCUtils.getConnection();

        try {

            // 开启事务
            connection.setAutoCommit(false);

            // 给fromName扣钱
            try {

                PreparedStatement preparedStatement1 = connection.prepareStatement("update account set money = money - ?  where name = ? and money >= ?");

                preparedStatement1.setInt(1, money);
                preparedStatement1.setString(2, fromName);
                preparedStatement1.setInt(3, money);

                // 执行
                int affectedRows = preparedStatement1.executeUpdate();

                if (affectedRows < 1) {
                    connection.rollback();
                    return false;
                }

                System.out.println("affectedRows:" + affectedRows);

                preparedStatement1.close();

            } catch (Exception ex) {
                ex.printStackTrace();
                connection.rollback();
                return false;

            }


//            int i = 1 / 0;

            // 给toName加钱
            try {
                PreparedStatement preparedStatement2 = connection.prepareStatement("update account set money = money + ?  where name = ?");
                preparedStatement2.setInt(1, money);
                preparedStatement2.setString(2, toName);

                int affectedRows2 = preparedStatement2.executeUpdate();

                if (affectedRows2 > 0) {
                    connection.commit();
                    return true;
                }
                preparedStatement2.close();

            } catch (Exception ex) {
                connection.rollback();
                ex.printStackTrace();
            }
        }catch (Exception ex) {

            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 关闭资源
        JDBCUtils.closeSource(connection, null, null);

        return false;



    }

}
